package com.csg.init;

import com.csg.entity.QuartzJob;
import com.csg.enums.JobStatus;
import com.csg.mapper.QuartzJobMapper;
import com.csg.service.IQuartzJobService;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class ApplicationInit implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationInit.class);

    @Resource
    private QuartzJobMapper quartzJobMapper;
    @Autowired
    private IQuartzJobService quartzJobService;
    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(String... args) throws Exception {
        loadJobToQuartz();
    }

    private void loadJobToQuartz() throws Exception {
        LOGGER.info("quartz job load...");
        List<QuartzJob> jobs = quartzJobMapper.listJob("");
        for(QuartzJob job : jobs) {
            quartzJobService.schedulerJob(job);
            if (JobStatus.PAUSED.equals(job.getTriggerState())) {
                scheduler.pauseJob(new JobKey(job.getJobName(), job.getJobGroup()));
            }
        }
    }
}
